<template>
  <div class="p-6 space-y-6">
    <!-- 页面标题 -->
    <div class="flex items-center justify-between">
      <h2 class="text-2xl font-bold text-gray-900 dark:text-gray-200">用户管理</h2>
      <button @click="showAddDialog = true" class="btn-primary flex items-center gap-2">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
        </svg>
        新增用户
      </button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="card">
      <div class="flex items-center gap-4">
        <div class="flex-1">
          <input v-model="searchQuery" type="text" placeholder="搜索用户名、邮箱..." class="input" />
        </div>
        <select v-model="statusFilter" class="input w-40">
          <option value="">全部状态</option>
          <option value="active">正常</option>
          <option value="inactive">禁用</option>
        </select>
        <button @click="searchUsers" class="btn-primary">搜索</button>
        <button @click="resetSearch" class="btn-secondary">重置</button>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="card">
      <div class="overflow-x-auto">
        <table class="w-full">
          <thead>
            <tr class="border-b border-gray-200 dark:border-gray-700">
              <th class="text-left py-3 px-4 font-semibold text-gray-900 dark:text-gray-200">用户信息</th>
              <th class="text-left py-3 px-4 font-semibold text-gray-900 dark:text-gray-200">角色</th>
              <th class="text-left py-3 px-4 font-semibold text-gray-900 dark:text-gray-200">部门</th>
              <th class="text-left py-3 px-4 font-semibold text-gray-900 dark:text-gray-200">状态</th>
              <th class="text-left py-3 px-4 font-semibold text-gray-900 dark:text-gray-200">最后登录</th>
              <th class="text-left py-3 px-4 font-semibold text-gray-900 dark:text-gray-200">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="user in filteredUsers"
              :key="user.id"
              class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-800/50">
              <td class="py-4 px-4">
                <div class="flex items-center gap-3">
                  <img :src="user.avatar" :alt="user.username" class="w-10 h-10 rounded-full" />
                  <div>
                    <p class="font-medium text-gray-900 dark:text-gray-200">{{ user.username }}</p>
                    <p class="text-sm text-gray-600 dark:text-gray-400">{{ user.email }}</p>
                  </div>
                </div>
              </td>
              <td class="py-4 px-4">
                <span
                  class="px-2 py-1 bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 text-sm rounded-full">
                  {{ user.role }}
                </span>
              </td>
              <td class="py-4 px-4 text-gray-900 dark:text-gray-200">{{ user.department }}</td>
              <td class="py-4 px-4">
                <span
                  :class="[
                    'px-2 py-1 text-sm rounded-full',
                    user.status === 'active'
                      ? 'bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200'
                      : 'bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200',
                  ]">
                  {{ user.status === 'active' ? '正常' : '禁用' }}
                </span>
              </td>
              <td class="py-4 px-4 text-gray-900 dark:text-gray-200">{{ user.lastLogin }}</td>
              <td class="py-4 px-4">
                <div class="flex items-center gap-2">
                  <button @click="editUser(user)" class="btn-secondary text-sm">编辑</button>
                  <button
                    @click="toggleUserStatus(user)"
                    :class="[
                      'text-sm rounded px-3 py-1 transition-colors',
                      user.status === 'active'
                        ? 'bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200 hover:bg-red-200 dark:hover:bg-red-800'
                        : 'bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200 hover:bg-green-200 dark:hover:bg-green-800',
                    ]">
                    {{ user.status === 'active' ? '禁用' : '启用' }}
                  </button>
                  <button
                    @click="deleteUser(user)"
                    class="text-sm bg-red-600 text-white rounded px-3 py-1 hover:bg-red-700 transition-colors">
                    删除
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- Element Plus 分页 -->
      <div class="flex justify-center mt-6">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalUsers"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="custom-pagination" />
      </div>
    </div>

    <!-- 新增/编辑用户弹窗 -->
    <el-dialog v-model="showAddDialog" :title="editingUser ? '编辑用户' : '新增用户'" width="500px">
      <form @submit.prevent="saveUser" class="space-y-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">用户名</label>
          <input v-model="userForm.username" type="text" class="input" required />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">邮箱</label>
          <input v-model="userForm.email" type="email" class="input" required />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">角色</label>
          <select v-model="userForm.role" class="input" required>
            <option value="">请选择角色</option>
            <option value="admin">管理员</option>
            <option value="user">普通用户</option>
            <option value="editor">编辑者</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">部门</label>
          <input v-model="userForm.department" type="text" class="input" />
        </div>
      </form>
      <template #footer>
        <div class="flex justify-end gap-3">
          <button @click="showAddDialog = false" class="btn-secondary">取消</button>
          <button @click="saveUser" class="btn-primary">保存</button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="system-user">
import { ref, computed } from 'vue'

defineOptions({ name: 'user' })

const searchQuery = ref('')
const statusFilter = ref('')
const showAddDialog = ref(false)
const editingUser = ref<any>(null)
const currentPage = ref(1)
const pageSize = ref(10)
const totalUsers = ref(100)

const userForm = ref({
  username: '',
  email: '',
  role: '',
  department: '',
})

// 模拟用户数据
const users = ref([
  {
    id: 1,
    username: 'admin',
    email: 'admin@example.com',
    role: '管理员',
    department: '技术部',
    status: 'active',
    lastLogin: '2024-01-15 10:30:00',
    avatar: 'https://api.dicebear.com/7.x/miniavs/svg?seed=admin',
  },
  {
    id: 2,
    username: 'user1',
    email: 'user1@example.com',
    role: '普通用户',
    department: '市场部',
    status: 'active',
    lastLogin: '2024-01-14 15:20:00',
    avatar: 'https://api.dicebear.com/7.x/miniavs/svg?seed=user1',
  },
])

const filteredUsers = computed(() => {
  let result = users.value

  if (searchQuery.value) {
    result = result.filter(
      (user) =>
        user.username.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
        user.email.toLowerCase().includes(searchQuery.value.toLowerCase()),
    )
  }

  if (statusFilter.value) {
    result = result.filter((user) => user.status === statusFilter.value)
  }

  return result
})

function searchUsers() {
  // 搜索逻辑
  console.log('搜索用户:', searchQuery.value)
}

function resetSearch() {
  searchQuery.value = ''
  statusFilter.value = ''
}

function editUser(user: any) {
  editingUser.value = user
  userForm.value = { ...user }
  showAddDialog.value = true
}

function saveUser() {
  if (editingUser.value) {
    // 更新用户
    const index = users.value.findIndex((u) => u.id === editingUser.value!.id)
    if (index !== -1) {
      users.value[index] = { ...users.value[index], ...userForm.value }
    }
  } else {
    // 新增用户
    const newUser = {
      id: Date.now(),
      ...userForm.value,
      status: 'active',
      lastLogin: '-',
      avatar: 'https://api.dicebear.com/7.x/miniavs/svg?seed=' + userForm.value.username,
    }
    users.value.push(newUser)
  }

  showAddDialog.value = false
  editingUser.value = null
  userForm.value = { username: '', email: '', role: '', department: '' }
}

function toggleUserStatus(user: any) {
  user.status = user.status === 'active' ? 'inactive' : 'active'
}

function deleteUser(user: any) {
  if (confirm('确定要删除这个用户吗？')) {
    users.value = users.value.filter((u) => u.id !== user.id)
  }
}

function handleSizeChange(size: number) {
  pageSize.value = size
  currentPage.value = 1
}

function handleCurrentChange(page: number) {
  currentPage.value = page
}
</script>

<style scoped>
.custom-pagination {
  --el-pagination-bg-color: transparent;
  --el-pagination-text-color: rgb(107 114 128);
  --el-pagination-border-radius: 8px;
  --el-pagination-button-color: rgb(107 114 128);
  --el-pagination-button-bg-color: transparent;
  --el-pagination-button-disabled-color: rgb(156 163 175);
  --el-pagination-button-disabled-bg-color: transparent;
  --el-pagination-hover-color: rgb(59 130 246);
  --el-pagination-hover-bg-color: rgb(239 246 255);
}

.dark .custom-pagination {
  --el-pagination-text-color: rgb(156 163 175);
  --el-pagination-button-color: rgb(156 163 175);
  --el-pagination-hover-color: rgb(96 165 250);
  --el-pagination-hover-bg-color: rgb(30 58 138);
}
</style>
